package com.lc.file.controller;

import cn.hutool.core.util.IdUtil;
import com.study.common.constant.LocalConstant;
import com.study.common.enums.FileSuffixEnum;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream;
import org.apache.commons.compress.compressors.gzip.GzipCompressorOutputStream;
import org.apache.commons.compress.utils.IOUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * @description: some desc
 * @author: LChuang
 * @date: 2023/9/8 10:10
 */
@Slf4j
@RestController
@RequestMapping("/file/download")
public class FileDownloadController {

    /**
     * 文件导出(txt,yml,json,zip....)
     */
    @GetMapping("/export")
    public void txt(HttpServletResponse response, @RequestParam("fileName") String fileName) {
        response.setCharacterEncoding("utf-8");
        // response.setContentType("application/multipart/form-data");
        response.setContentType("application/octet-stream");
        /*
        下载不同的文件需要设置不同的ContentType值，
        也可设置为application/octet-stream以流的形式进行输出，不过可能需要前端配合写"流文件下载方法"
         */
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        response.setHeader("Content-Disposition", "attachment;filename=" + IdUtil.fastSimpleUUID() + suffix);
        try {
            FileInputStream inputStream = new FileInputStream(LocalConstant.LOCAL_UPLOAD_PATH + fileName);
            byte[] buffer = new byte[1024]; // 缓冲区大小
            int bytesRead;
            OutputStream os = response.getOutputStream();
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            os.flush();
            os.close();
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }
    }
}
